<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/25/24
 * Time: 1:54 PM
 */

namespace App\Console\Commands;

use App\Models\WechatKfKeyword;
use App\Services\KfAccountService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\WechatUser;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;
use App\Models\WechatPush as pushModel;
use Illuminate\Support\Facades\Log;


/**
 * 企业微信推送消息
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatPush extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:push {minute}';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '企业微信推送消息';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 微信推送
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $minute = (int)$this->argument('minute') ?? 0;
        if (!$minute) {

            return false;
        }

        $replyAt = Carbon::now()->subHours(48)->toDateTimeString();
        $list    = WechatUser::query()
            ->where('status', WechatUser::STATUS_YES)
            ->where('reply_at', '>=', $replyAt)
            ->get();
        if ($list->isEmpty()) {

            return false;
        }
        /**
         * 间隔15分钟  30分钟  1.5小时  4小时 8小时
         */
        Log::info('====>企微代开发客服消息推送，发送间隔：' . $minute);
        $client  = new Client();
        $service = new KfAccountService();
        $i       = 0;
        foreach ($list as $item) {
            if (!$item->reply_at) {
                continue;
            }
            // 回复时间
            $rTime = Carbon::parse($item->reply_at ?? '');
            $nTime = Carbon::now();
            // 如果间隔时间不相等则不发
            if ($nTime->diffInMinutes($rTime) != $minute) {
                continue;
            }

            // 推送内容
            $content = pushModel::query()
                ->where('corp_id', $item->corp_id)
                ->where('open_kfid', $item->open_kfid)
                ->where('push_time', $minute)
                ->first();
            if (!$content) {
                continue;
            }

            switch ($content->msg_type) {
                case WechatKfKeyword::MSG_LINK :
                    $body = [
                        'headers'            => ['Content-Type' => 'application/json'],
                        RequestOptions::JSON => [
                            'touser'    => $item->user_id,
                            'open_kfid' => $item->open_kfid,
                            'msgtype'   => 'link',
                            'link'      => [
                                'title'          => $content->title,
                                'desc'           => $content->desc,
                                'url'            => $content->url,
                                'thumb_media_id' => $content->media_id
                            ]
                        ]
                    ];
                    break;
                case WechatKfKeyword::MSG_MINIPROGRAM :
                    $body = [
                        'headers'            => ['Content-Type' => 'application/json'],
                        RequestOptions::JSON => [
                            'touser'      => $item->user_id,
                            'open_kfid'   => $item->open_kfid,
                            'msgtype'     => 'miniprogram',
                            'miniprogram' => [
                                'appid'          => $content->appid,
                                'title'          => $content->title,
                                'pagepath'       => $content->url,
                                'thumb_media_id' => $content->media_id
                            ]
                        ]
                    ];
                    break;
            }

            $response = $client->request(
                'POST',
                sprintf(
                    config('corp_wechat.send_msg'),
                    $service->getReplaceAccessToken($item->corp_id)
                ),
                $body
            );
            if ($response->getStatusCode() != 200) {
                continue;
            }
            $data    = $response->getBody()->getContents();
            $content = json_decode($data, true);
            if (($content['errcode'] ?? -1) != 0) {
                continue;
            }
            $i++;
        }
        Log::info('====>企微代开发客服消息推送完成，推送成功：' . $i);
    }
}
